# ！ /usr/bin/python3
# -*- coding:utf-8 -*-
import os
import logging
from ApiManager.models import TestCaseInfo
import json
from httprunner.api import HttpRunner
from httprunner import report
from ApiAutoTest import celery_app
from django.conf import settings
from ApiManager.models import DebugTalk, EnvInfo

logger = logging.getLogger('ApiAutoTest')
base_dir = settings.BASE_DIR
project_dir = os.path.join(base_dir, f"ApiAutoTest/../project")


@celery_app.task
def runCaseWorker(case_list):
    """
    异步执行用例
    :param case_list:
    :return:
    """
    flag = True
    runner = HttpRunner(failfast=False,  # 设置为 True 时，测试在首次遇到错误或失败时会停止运行；默认值为 False
                        save_tests=True,  # 设置为 True 时，会将运行过程中的状态（loaded/parsed/summary）保存为 JSON 文件，存储于 logs 目录下；
                        log_level="INFO",
                        log_file=os.path.join(base_dir, f"logs/httpRunner.log"))  # 设置日志文件路径，指定后将同时输出日志文件
    for case_info in case_list:
        case_id = int(case_info.get("pk"))
        case_type = case_info.get('fields').get("type_case")
        case_name = case_info.get('fields').get("name")
        module_id = int(case_info.get('fields').get('belong_module'))
        project_id = int(case_info.get('fields').get('belong_project'))
        logger.info(f"获取待运行的用例类型为：{case_type}；项目Id为：{project_id}；模块Id为：{module_id}；用例Id为：{case_id}；")
        if case_type == 'single':
            run_dir = 'api'
        else:
            run_dir = 'testcases'
        api_path = os.path.join(project_dir, f'ApiProject{project_id}/ApiModule{module_id}/{run_dir}/test{case_id}.yml')
        # 执行测试用例
        report_path_old = runner.run(api_path)
        # 由于执行run时也会执行render_html_report生成一份默认报告，该报告无法自定义定制，不符合需求，因此删除
        os.unlink(report_path_old)
        # 获取用例执行详细结果
        summary = runner.summary
        logger.info(f'测试结果json内容--{json.dumps(summary)}')
        report_path = report.render_html_report(
            summary=summary,
            report_template=os.path.join(base_dir, f'ApiAutoTest/../report_template.html'),
            report_file=os.path.join(base_dir, f'reports/用例{case_id}.html')
        )
        logger.info(f"测试报告html路径--{report_path}")
        obj = TestCaseInfo.objects.get(id=case_id)
        if summary['success']:
            obj.status_case = 1
            logger.info(f'{case_name}用例执行成功')
        else:
            obj.status_case = -1
            flag = False
            logger.info(f'{case_name}用例执行失败')
        obj.report_path = report_path
        obj.save()
    return flag


@celery_app.task
def moduleAddWorker(project_id, module_id):
    """
    异步生成模块文档
    :param project_id:
    :param module_id:
    :return:
    """
    project_case_dir = os.path.join(project_dir, f'ApiProject{project_id}')
    os.chdir(project_case_dir)
    os.system(f"hrun --startproject ApiModule{module_id}")
    return None


def caseConfigAdd(debugTalkInfo, envInfo):
    """
    添加用例配置
    :param debugTalkInfo:
    :param envInfo:
    :return:
    """
    debugtalk_id = debugTalkInfo.get('id')
    debugtalk_obj = DebugTalk.objects.get(id=debugtalk_id)
    debugtalk_obj.belong_module_id = debugTalkInfo.get('belong_module')
    debugtalk_obj.belong_project_id = debugTalkInfo.get('belong_project')
    debugtalk_obj.debugtalk = debugTalkInfo.get('debugtalk')
    debugtalk_obj.save()
    # 保存env到数据库
    env_id = envInfo.get('id')
    env_obj = EnvInfo.objects.get(id=env_id)
    env_obj.belong_module_id = envInfo.get('belong_module')
    env_obj.belong_project_id = envInfo.get('belong_project')
    env_obj.content = envInfo.get('content')
    env_obj.save()
    # 保存debugtalk内容到项目debugtaik.py文本中
    debugtalk_path = os.path.join(project_dir, f'ApiProject{debugTalkInfo.get("belong_project")}/ApiModule{debugTalkInfo.get("belong_module")}/debugtalk.py')
    logger.info(f'获取debugtalk.py的路径：{debugtalk_path}')
    with open(debugtalk_path, 'w', encoding='utf-8') as f:
        f.write(debugTalkInfo.get('debugtalk'))
    # 保存env内容到项目.env文本中
    env_path = os.path.join(project_dir, f'ApiProject{debugTalkInfo.get("belong_project")}/ApiModule{debugTalkInfo.get("belong_module")}/.env')
    logger.info(f'获取.evn的路径：{env_path}')
    with open(env_path, 'w', encoding='utf-8') as f:
        f.write(envInfo.get('content'))
